<?php

namespace app\service\v1;

use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;

// token基类
class BaseToken
{
    /**
     * * 生成token
     * 1、32个字符组成的随机字符串
     * 2、当前的时间戳
     * 3、盐
     * 4、合并以上三组，并MD5加密
     * getRandChar()位于应用目录的common.php中
     * @return string
     */
    public static function generateToken(): string
    {
        $randChars = getRandChar(32);
        $timesTamp = Request::time();
        $salt = Config::get('util.token_salt');

        return md5($randChars.$timesTamp.$salt);
    }

    /**
     * 检测token是否过期
     * @param string $token
     * @return bool
     */
    public static function checkToken(string $token): bool
    {
        $exist = Cache::get($token);
        if (!$exist) {
            return false;
        }
        return true;
    }

    /**
     * 清除token
     * @return bool
     */
    public static function removeToken(): bool
    {
        $token = Request::header('token');
        Cache::delete($token);
        return true;
    }

    /**
     * 缓存获取当前用户id
     * @return mixed
     * @throws Exception
     */
    public static function getCurrentUID() {
        return self::getInfoByToken('uid');
    }

    /**
     * 基于token获取其他信息
     * @param string $key
     * @return mixed
     * @throws Exception
     */
    public static function getInfoByToken(string $key) {
        $token = Request::header('token');
        if (!$token) {
            throw new HttpException(401, 'token不能为空');
        }
        $info = Cache::get($token);
        if (!$info) {
            throw new HttpException(401, 'token已失效');
        } else {
            if (!is_array($info)) {
                $info = json_decode($info, true);
            }
            if (array_key_exists($key, $info)) {
                return $info[$key];
            }
            throw new Exception('非法操作');
        }
    }
}